package com.rfsp.common.service;

import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcOperations;
import org.springframework.session.FindByIndexNameSessionRepository;
import org.springframework.session.Session;
import org.springframework.session.jdbc.JdbcIndexedSessionRepository;
import org.springframework.session.jdbc.JdbcOperationsSessionRepository;
import org.springframework.stereotype.Service;

import com.rfsp.common.base.BaseService;
import com.rfsp.common.mapper.ParamMapper;
import com.rfsp.common.mapper.UserMapper;
import com.rfsp.common.pojo.po.UserPO;

@Service
public class UserService extends BaseService<UserPO> {

	public Logger log = LoggerFactory.getLogger(UserService.class);
	
	@Autowired
	UserMapper mapper;
	@Autowired
	ParamMapper paramMapper;

	@Autowired
	FindByIndexNameSessionRepository<? extends Session> sessionRepository;

	public void kickOutUser(String userCode){
		// 1. 关键：通过索引查询该用户的所有 Session（索引名固定）
		String indexName = FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME;
		Map<String, ? extends Session> userSessions = sessionRepository.findByIndexNameAndIndexValue(indexName, userCode);

		if (userSessions.isEmpty()) {
			// 该用户无活跃 Session，直接返回
			return;
		}

		// 2. 遍历所有 Session，批量失效（删除 Redis 中的 Session 数据和索引）
		userSessions.keySet().forEach(sessionId -> {
			// 失效 Session（会自动删除 Redis 中的 sessionKey 和 indexKey）
			sessionRepository.deleteById(sessionId);
		});
	}
	public List<UserPO> getUserByOrgId(Long orgId){
		return mapper.getUserByOrgId(orgId);
	}
	
	
	public UserPO getUserByUserCodeAndPwd (String userCode, String password){
		return mapper.getUserByNameAndPwd(userCode, password);
	}
	
	public UserPO getUser (String userCode){
		return mapper.getUserByUserCode(userCode);
	}
	

	public List<String> queryRolesByUser (String userCode){
		List<String> r = mapper.getUserRole(userCode);
		return  r;
	}

	
	public List<String> queryRoleNamesByUser (String userCode){
		List<String> rname = mapper.getUserRoleName(userCode);
		return rname;
	}
	
	public String getUserSession (String userCode){
		String sessionId = mapper.getUserSession(userCode);
		return sessionId;
	}
	
	
	public UserPO getUserByCaSubjection(String subjectDN) {
		return mapper.getUserByCaSubjection(subjectDN);
	}

	public UserPO getUserByCaSubjectionAndUserStatusNot4(String subjectDN) {
		return mapper.getUserByCaSubjectionAndUserStatusNot4(subjectDN);
	}
}
